﻿using Mes_app;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Mes_app_control
{
    public partial class Main_Form : Form
    {
        // 计数器：记录定时器执行次数（暂停后恢复不重置，终止后重置）
        private int _executeCount = 0;
        // 标记定时器当前状态（避免重复操作）
        private bool _isPaused = false;
        // 计数器（可选，用于统计执行次数）
        private int _taskCount = 0;
        ControlCommandDal controlCommandDal = new ControlCommandDal();
        public Main_Form()
        {
            InitializeComponent();
            // 初始化界面提示
            lblStatus.Text = "状态：定时器未启动\n执行次数：0\n当前时间：-";
            // 初始化页面（可选）
            nudInterval.Minimum = 1000;    // 最小间隔 5秒
            nudInterval.Maximum = 10000;   // 最大间隔 10 秒
            nudInterval.Value = 5000;     // 默认 5 秒
            btnStop.Enabled = false;      // 初始时停止按钮不可用

            this.DataGV.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.DataGV_CellFormatting);
        }

        private void Btn_query_Click(object sender, EventArgs e)
        {
            Query();
        }

        private void Main_Form_Load(object sender, EventArgs e)
        {
            this.Width = 1000;
            this.Height = 600;
            Date1.Text = DateTime.Now.AddDays(-15).ToShortDateString();
            Date2.Text = DateTime.Now.ToString();

            Query();
        }


        private void Query()
        {
            ControlCommand controlCommand = new ControlCommand();
            if (TextBox_machine_no.Text.Trim() != "")
                controlCommand.machine_no = TextBox_machine_no.Text.Trim();

            if (TextBox_machine_address.Text.Trim() != "")
                controlCommand.machine_address = TextBox_machine_address.Text.Trim();

          //  if (TextBox_supplier_no.Text.Trim() != "")
          //      controlCommand.supplier_no = TextBox_supplier_no.Text.Trim();

            string str_date1 = Date1.Value.ToString("yyyy-MM-dd");
            string str_date2 = Date2.Value.ToString("yyyy-MM-dd");

            if (RadioButton_0.Checked)
                controlCommand.status = 0;
            if (RadioButton_1.Checked)
                controlCommand.status = 1;
            if (RadioButton_2.Checked)
                controlCommand.status = 2;
            if (RadioButton_all.Checked)
                controlCommand.status = 3;

            if (radio_diao.Checked)
                controlCommand.supplier_no = "diao";
            if (radio_jiatie.Checked)
                controlCommand.supplier_no = "jiatie";

            DataSet ds = controlCommandDal.GetDataSet(str_date1, str_date2, controlCommand);
            //  DataSet ds = SqlHelper.ExecuteDataSet(sqlValue, parameters);
            //id,machine_no,machine_name,machine_address,command_param,supplier_no,create_time,status,exec_time
            if (ds.Tables.Count > 0)
            {
                DataGV.DataSource = ds.Tables[0];

                DataGV.Columns["id"].HeaderText = "ID";
                DataGV.Columns["machine_no"].HeaderText = "设备编号";
                DataGV.Columns["machine_name"].HeaderText = "设备名称";
                DataGV.Columns["machine_address"].HeaderText = "设备地址";
                DataGV.Columns["command_param"].HeaderText = "数据项";
                DataGV.Columns["supplier_no"].HeaderText = "设备商";
                DataGV.Columns["create_time"].HeaderText = "创建时间";
                DataGV.Columns["status"].HeaderText = "状态";
                DataGV.Columns["exec_time"].HeaderText = "执行时间";
                DataGV.Columns["command_value"].HeaderText = "指令值";
                DataGV.Columns["description"].HeaderText = "描述";

                DataGV.Columns["machine_no"].Width = 90;
                DataGV.Columns["machine_name"].Width = 90;
                DataGV.Columns["machine_address"].Width = 150;
                DataGV.Columns["command_param"].Width = 90;
                DataGV.Columns["supplier_no"].Width = 90;
                DataGV.Columns["create_time"].Width = 120;
                DataGV.Columns["status"].Width = 80;
                DataGV.Columns["exec_time"].Width = 120;
                DataGV.Columns["command_value"].Width = 70;
                DataGV.Columns["description"].Width = 80;

                DataGV.Columns["id"].Visible = false;
                DataGV.Columns["machine_port"].Visible = false;
                DataGV.Columns["cnc_num"].Visible = false;
                DataGV.Columns["description"].Visible = false;

                //设置数据表格为只读
                DataGV.ReadOnly = true;
                //不允许添加行
                DataGV.AllowUserToAddRows = false;
                //背景为白色
                DataGV.BackgroundColor = Color.White;
                //只允许选中单行
                DataGV.MultiSelect = false;
                //整行选中
                DataGV.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

                if (ds != null && ds.Tables.Count > 1)
                    DataGV.CurrentCell = DataGV.Rows[0].Cells[1];
            }
        }

        private void DataGV_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // 检查是否是 status 列且值不为null
            if (DataGV.Columns[e.ColumnIndex].Name == "status" && e.Value != null)
            {
                switch (e.Value.ToString())
                {
                    case "0":
                        e.Value = "未执行";
                        e.FormattingApplied = true;
                        break;
                    case "1":
                        e.Value = "执行成功";
                        e.FormattingApplied = true;
                        break;
                    case "2":
                        e.Value = "执行失败";
                        e.FormattingApplied = true;
                        break;
                    default:
                        e.Value = "未知状态";
                        e.FormattingApplied = true;
                        break;
                }
            }
        }

        private void Btn_add_Click(object sender, EventArgs e)
        {
            if (radio_diao.Checked)
            {
                Control_commd_diao_Form control_commd_Form = new Control_commd_diao_Form(0);
                //  this.Hide();
                control_commd_Form.ShowDialog();
            }
            else
            if (radio_jiatie.Checked)
             {
                Control_commd_jiatie_Form control_commd_Form = new Control_commd_jiatie_Form(0);
                //  this.Hide();
                control_commd_Form.ShowDialog();
            }

            //Control_commd_diao_Form control_commd_Form = new Control_commd_diao_Form(0);
            //  this.Hide();
            //control_commd_Form.ShowDialog();
            Query();
        }

        private void Btn_edit_Click(object sender, EventArgs e)
        {
            if (DataGV.CurrentCell == null)
                return;
            int rowindex = DataGV.CurrentRow.Index;
            int id = Convert.ToInt32(DataGV.Rows[rowindex].Cells["id"].Value);

           if (DataGV.Rows.Count == 0)
                return;
            int Row_i = DataGV.CurrentCell.RowIndex;
            int Cell_i = DataGV.CurrentCell.ColumnIndex;

            string supplier_no = DataGV.Rows[rowindex].Cells["supplier_no"].Value.ToString();
            if (supplier_no == "diao")
            {
                Control_commd_diao_Form control_commd_Form = new Control_commd_diao_Form(id);
                control_commd_Form.ShowDialog();
            }
            else
            if 
                (supplier_no == "jiatie")
            {
                Control_commd_jiatie_Form control_commd_Form = new Control_commd_jiatie_Form(id);
                control_commd_Form.ShowDialog();
            }
            Query();

         //   if (Row_i != 0)
         //       DataGV.CurrentCell = DataGV.Rows[Row_i].Cells[Cell_i];
        }

        private void Btn_delete_Click(object sender, EventArgs e)
        {
            int rowindex = DataGV.CurrentRow.Index;
            int id = Convert.ToInt32(DataGV.Rows[rowindex].Cells["id"].Value);

            if (DataGV.CurrentCell == null)
                return;

            int Row_i = DataGV.CurrentCell.RowIndex;
            int Cell_i = DataGV.CurrentCell.ColumnIndex;
            int rowCount = DataGV.RowCount - 1;

            if (MessageBox.Show("确认删除？", "是否删除？", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.OK)
            {
                if (controlCommandDal.Delete(id) > 0)
                    MessageBox.Show("删除成功");
                Query();
            };
            if (Row_i != 0)
            {
                if (Row_i == rowCount)
                    Row_i = Row_i - 1;
                DataGV.CurrentCell = DataGV.Rows[Row_i].Cells[Cell_i];
            }
        }

        private void Btn_exit_Click(object sender, EventArgs e)
        {
            Close();
        }


        private void DataGV_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int rowindex = DataGV.CurrentRow.Index;
            int id = Convert.ToInt32(DataGV.Rows[rowindex].Cells["id"].Value);

            Control_commd_diao_Form control_commd_Form = new Control_commd_diao_Form(id);
            //  this.Hide();
            control_commd_Form.ShowDialog();
            Query();
        }

        #region 启动按钮事件
        private void Btn_start_Click(object sender, EventArgs e)
        {
            // 情况 1：首次启动（未启动过或已终止）
            if (!timerTask.Enabled && !_isPaused)
            {
                // 设置定时器间隔（从数值框读取）
                timerTask.Interval = (int)nudInterval.Value;
                // 重置计数器（首次启动/终止后启动，计数器归零）
                _executeCount = 0;
            }
            // 情况 2：从暂停状态恢复启动
            else if (_isPaused)
            {
                // 保留之前的计数器和间隔，直接启动
            }

            // 启动定时器
            timerTask.Start();
            // 更新状态和按钮
            _isPaused = false;
            lblStatus.Text = $"状态：定时器运行中\n执行次数：{_executeCount}\n当前时间：{DateTime.Now:HH:mm:ss.fff}";
            UpdateButtonStates(true); // 运行中：禁用启动，启用暂停/终止
        }
        #endregion

        #region 暂停按钮事件
        private void Btn_pause_Click(object sender, EventArgs e)
        {
            // 停止定时器
            timerTask.Stop();
            // 重置状态（计数器、暂停标记）
            _executeCount = 0;
            _isPaused = false;
            // 恢复初始界面
            lblStatus.Text = "状态：定时器已终止\n执行次数：0\n当前时间：-";
            UpdateButtonStates(false, isStopped: true); // 终止后：仅启用启动
        }
        #endregion

        #region 定时器触发事件（核心任务逻辑）
        private void timerTask_Tick(object sender, EventArgs e)
        {
            // 1. 计数器自增
            _executeCount++;

            // 2. 执行定时任务（示例：更新时间、业务逻辑）
            string currentTime = DateTime.Now.ToString("HH:mm:ss.fff");
            lblStatus.Text = $"状态：定时器运行中\n执行次数：{_executeCount}\n当前时间：{currentTime}";

            // 3. 执行任务（示例：调用外部方法）
            ExecuteCommand();
            // 扩展：添加你的业务逻辑（如查询数据库、调用接口、文件处理等）
            // 注意：耗时操作需用 async/await 避免 UI 卡顿，示例如下：
            // await DoBusinessTaskAsync();
        }
        #endregion

        #region 辅助方法：更新按钮状态（避免重复代码）
        /// <summary>
        /// 更新按钮启用/禁用状态
        /// </summary>
        /// <param name="isRunning">是否正在运行</param>
        /// <param name="isStopped">是否已终止（优先级更高）</param>
        private void UpdateButtonStates(bool isRunning, bool isStopped = false)
        {
            if (isStopped)
            {
                btnStart.Enabled = true;
                btnPause.Enabled = false;
                btnStop.Enabled = false;
            }
            else
            {
                btnStart.Enabled = !isRunning; // 运行中禁用启动，暂停/终止时启用
                btnPause.Enabled = isRunning;  // 仅运行中启用暂停
                btnStop.Enabled = true;        // 启动后始终启用终止（随时可终止）
            }
        }
        #endregion

        #region 可选：动态修改定时间隔（无需停止）
        private void nudInterval_ValueChanged(object sender, EventArgs e)
        {
            if (timerTask.Enabled)
            {
                // 动态修改间隔（即时生效，无需停止定时器）
                timerTask.Interval = (int)nudInterval.Value;
                lblStatus.Text += $"\n间隔已更新为：{nudInterval.Value} 毫秒";
            }
        }
        #endregion

        #region 窗体关闭时释放资源（避免内存泄漏）
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            timerTask?.Stop();
            timerTask?.Dispose();
        }
        #endregion
        private void ExecuteCommand()
        {
            List<ControlCommand> list = controlCommandDal.GetList();
            list = list.Where(x => x.status == 0).ToList();
            foreach (var item in list)
            {

                if (item.supplier_no == "diao")//迪奥
                {
                    Control_commd_diao_Form commandForm = new Control_commd_diao_Form(item.id);
                    // 调用 ConnectAndExecuteCommand 方法
                    bool success = commandForm.ConnectAndExecuteCommand_diao(
                            item.machine_address,  // 机器地址
                            item.command_param,   // 命令参数
                            item.command_value   // 命令值
                        );

                        // 处理返回结果
                        if (success)
                        {
                            item.status = 1;//执行成功
                            controlCommandDal.UpdateStatus(item);
                            Label_show.Text = "连接并执行命令成功！";
                            Query();
                           //MessageBox.Show("连接并执行命令成功！");
                    }
                        else
                        {
                            item.status = 2;//执行失败
                            controlCommandDal.UpdateStatus(item);
                            Label_show.Text = "连接并执行命令成功！";
                            Query();
                        // MessageBox.Show("连接或执行命令失败！");

                    }
                 }
                if (item.supplier_no == "jiatie")//佳铁
                {
                    Control_commd_jiatie_Form commandForm = new Control_commd_jiatie_Form(item.id);
                    // 调用 ConnectAndExecuteCommand 方法
                    // public bool ConnectAndExecuteCommand(string machineAddress, int machinePort, int cncNum, string commandParam, string commandValue)
                    bool success = commandForm.ConnectAndExecuteCommand_jiatie(
                        item.machine_address,  // 机器地址
                        item.machine_port,     // 端口
                        item.cnc_num,          // CNC编号
                        item.command_param,   // 命令参数
                        item.command_value   // 命令值
                    );

                    // 处理返回结果
                    if (success)
                    {
                        item.status = 1;//执行成功
                        controlCommandDal.UpdateStatus(item);
                        Label_show.Text = "连接并执行命令成功！";
                        Query();
                        //MessageBox.Show("连接并执行命令成功！");
                    }
                    else
                    {
                        item.status = 2;//执行失败
                        controlCommandDal.UpdateStatus(item);
                        Label_show.Text = "连接并执行命令成功！";
                        Query();
                        // MessageBox.Show("连接或执行命令失败！");

                    }

                }
         
            }

        }


        private void DataGV_CellDoubleClick_1(object sender, DataGridViewCellEventArgs e)
        {
            int index = DataGV.CurrentRow.Index;
            int id = Convert.ToInt32(DataGV.Rows[index].Cells["id"].Value);

            string supplier_no = DataGV.Rows[index].Cells["supplier_no"].Value.ToString();
            if (supplier_no == "diao")
            {
                Control_commd_diao_Form control_commd_Form = new Control_commd_diao_Form(id);
                control_commd_Form.ShowDialog();
            }
            else
            if
                (supplier_no == "jiatie")
            {
                Control_commd_jiatie_Form control_commd_Form = new Control_commd_jiatie_Form(id);
                control_commd_Form.ShowDialog();
            }

           // Control_commd_diao_Form commandForm = new Control_commd_diao_Form(id);
          //  commandForm.ShowDialog();
        }

        private void Btn_test_Click(object sender, EventArgs e)
        {
            ExecuteCommand();
        }
    }
}
